package com.example.excel.controller;

import com.alibaba.excel.EasyExcel;
import com.example.excel.entity.ForecastElectricityRevenue;
import com.example.excel.listener.ExcelModelListener;
import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;

/**
 * @author dingfeng
 * @version 1.0
 * @DEC
 * @date 2022-03-31 15:28
 */
@RestController
public class ExcelController {

    @Autowired
    private JdbcTemplate jdbcTemplate;



    @GetMapping("downloadTemplate")
    public void downloadTemplate(HttpServletResponse response) {
        try (InputStream inputStream = ExcelController.class.getClassLoader().getResourceAsStream("files/template.xlsx");
             ServletOutputStream outputStream = response.getOutputStream()) {
            response.setContentType("application/vnd.ms-excel");
            response.setCharacterEncoding("utf-8");
            response.setHeader("Content-disposition", "attachment;filename=template.xlsx");
            IOUtils.copy(inputStream, outputStream);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @PostMapping("upload")
    @ResponseBody
    public String upload(MultipartFile file) throws IOException {
        EasyExcel.read(file.getInputStream(), ForecastElectricityRevenue.class, new ExcelModelListener(jdbcTemplate)).sheet().doRead();
        return "success";
    }
}
